import { TOKEN_KEY } from "@/const"
import { useUserInfo } from "@/stores/userInfo"
import { useRequestOldRoutes } from "../stores/requestOldRoutes"
import { Local, Session } from "@/utils"
import {apiSysMenuLoginMenuTreeGet} from '@/api/sys/sysMenu'
import type { ResType } from "@/api/types"
import {dynamicRoutes, notFoundAndNoPower} from './routes'
import router,{ formatFlatteningRoutes, formatTwoStageRoutes } from "."
import type { RouteRecord } from "vue-router"
import { useRoutesList } from "@/stores/routesList"
import { useTagsViewRoutes } from "@/stores/tagsViewRoutes"
export const initBackEndControlRoutes = async ()=>{
    if( !Local.get(TOKEN_KEY)){
        return false
    }
    
    const userInfo = useUserInfo()
    // 初始化信息
    await userInfo.setUserInfos()
    await userInfo.setConstList()
    await userInfo.setDictList()
    // 调用接口获取菜单树
    const res = await getBackEndControlRoutes()
    // 代表用户是登录的存在token，但是没有菜单权限
    if(!res || res.length == 0) return true
    // 保存原始路由信息
    useRequestOldRoutes().setRequestOldRoutes(res)
    // 针对原始路由处理期component引入组件
    dynamicRoutes[0].children = await backEndComponent(res)
    // 添加路由
    await setAddRoute()
    // 设置路由到pinia中保存
    setFilterMenuAndCacheTagsViewRoutes()
}

// 获取菜单树
export const getBackEndControlRoutes = async ()=>{
    const res = await apiSysMenuLoginMenuTreeGet() as ResType<Array<any>>
    return res.data.result
}

const layouModules: any = import.meta.glob('../layout/routerView/*.{vue,tsx}');
const viewsModules: any = import.meta.glob('../views/**/*.{vue,tsx}');
const dynamicModules: Record<string, Function> = Object.assign({ ...layouModules }, { ...viewsModules });

export const backEndComponent = async (routes:any)=>{
    if(!routes) return []
    return routes.map((item:any)=>{
        if(!item.path) item.path = "" //防止路由没有该属性报错
        if(item.component) {
            item.component = dynamicImport(dynamicModules,item.component as string)
        }
        Array.isArray(item.children) && backEndComponent(item.children)
        return item
    })
}

export const dynamicImport = (dynamicViewsModules:Record<string,Function>,component:string)=>{
    const keys = Object.keys(dynamicViewsModules)
    // 过滤符合要求的
    const matchKeys = keys.filter(key=>{
        const k = key.replace(/..\/views|../, '');
        return k.startsWith(`${component}`) || k.startsWith(`/${component}`);
    })
    if(matchKeys?.length === 1){
        const matchKey = matchKeys[0];
        return dynamicViewsModules[matchKey] // 匹配到唯一的组件
    }
    if(matchKeys.length > 1) return false
}

export const setAddRoute =async ()=>{
	await setFilterRouteEnd().forEach((route: RouteRecord) => {
		router.addRoute(route);
	});
}
export const setFilterRouteEnd = () =>{
	let filterRouteEnd: any = formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes));
	// notFoundAndNoPower 防止 404、401 不在 layout 布局中，不设置的话，404、401 界面将全屏显示
	// 关联问题 No match found for location with path 'xxx'
	filterRouteEnd[0].children = [...filterRouteEnd[0].children,...notFoundAndNoPower];
	return filterRouteEnd;
}

export const setFilterMenuAndCacheTagsViewRoutes = ()=>{
    const routesList = useRoutesList()
    // 存储格式化后的菜单数据
    routesList.setRoutesList(dynamicRoutes[0].children as any)
    setCacheTagsViewRoutes()
}

export const setCacheTagsViewRoutes = ()=>{
    const tagsViewRoutes = useTagsViewRoutes()
    tagsViewRoutes.setTagsViewRoutes(formatTwoStageRoutes(formatFlatteningRoutes(dynamicRoutes))[0].children)
}